﻿using SanlieHash.Fast;
using System;

namespace wuo._typ
{
    internal class nomarl_rt
    {
        public static string en_string(object s)
        {
            var _s = (string)s;
            if (_s == null || _s.Length == 0) return (char)typdefs.STRING + esize(0);
            return (char)typdefs.STRING +esize(_s.Length) +  (s as string);
        }
        public static string de_string(ref string s)
        {
            var size = dsize(ref s);
            if (size == 0) return string.Empty;
            var t = s.Substring(0, size);
            s = s.Substring(size+1);
            return t;
        }
        public static string en_int(object s)
        {
            return (char)typdefs.INT + esize((int)s);
        }
        public static int de_int(ref string s)
        {
            return dsize(ref s);
        }

        internal const char ZORE = '0';
        internal static string esize(int size)
        {
            if (size == 0) return (char)(64 + 57) + string.Empty;

            var hex = FastEncode.EncodeHex(BitConverter.GetBytes(size));
            var lt_size = 8 - hex.TrimStart(ZORE).Length;
            var rt_size = 8 - hex.TrimEnd(ZORE).Length;
            return (char)(64 + ((lt_size << 3) | rt_size)) + hex.Trim(ZORE);
        }
        internal static int dsize(ref string msg)
        {
            var size = (byte)msg[0] - 64;
            var lt_size = (size >> 3) & 0b111;
            var rt_size = size & 0b111;
            msg = msg.Substring(1);
            size = 8 - lt_size - rt_size;
            if (size == 0) return 0;

            var _msg = msg.Substring(0, size);
            msg = msg.Substring(size);
            for (var i = 0; i < lt_size; i++) _msg = ZORE + _msg;
            for (var i = 0; i < rt_size; i++) _msg += ZORE;
            return BitConverter.ToInt32(FastEncode.DecodeHex(_msg), 0);
        }
    }
}
